from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from platforms.models import *
from customer.models import *
from rider.models import *
from werkzeug.security import check_password_hash, generate_password_hash
from django.conf import settings
import jwt
import time
from configuration.jwt_decode import check_login
from business.models import *
from datetime import datetime
from django.core.paginator import Paginator
# Create your views here.

# 注册
class ZhuView(APIView):
    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')

        if not all([username, password]):
            return Response({
                'code': 40000,
                'message': '获取的数据为空'
            })

        # 判断唯一性
        pal = PlaUserModel.objects.filter(c_name=username).first()
        if not pal:
            passwords = generate_password_hash(password)
            PlaUserModel.objects.create(c_name=username,password=passwords)
            return Response({
                'code':20000,
                'message':'注册成功'
            })

# 登入
class PlaUserView(APIView):
    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')

        if not all([username,password]):
            return Response({
                'code':40000,
                'message':'获取的数据为空'
            })
        try:
            user = PlaUserModel.objects.get(c_name=username)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':40000,
                'message':'没有此用户'
            })

        if check_password_hash(user.password,password):
            token = jwt.encode({
                'uid': user.id,
                'username': user.c_name,
                'exp': time.time() + 720000
            }, key=settings.SECRET_KEY, algorithm='HS256')

            return Response({
                'code':20000,
                'message':'登入成功',
                'data':{
                    'token': token,
                    "character": '大佬',
                    'uid': user.id
                },

            })

        return Response({
            'code':40000,
            'message':'密码错误'
        })

class UserView(APIView):
    def get(self,request):
        # 接受前端token
        deng = request.query_params.get('token')
        key = settings.SECRET_KEY
        token = jwt.decode(deng, key=key, algorithms='HS256')
        print('token的', token)

        u_id = token.get("uid")
        print('dasdasd',u_id)

        try:
            user = PlaUserModel.objects.get(id=u_id)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'roles': '超级用户',
                'name': user.c_name,
                'avatar': user.portrait,
            }

        })

# 退出登入
class LogoutView(APIView):
    def post(self,request):
        return Response({
            "code":20000,
            "message":"退出登录成功"
        })

# 获取所有商家
class UserAllView(APIView):
    def get(self,request):

        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')

        bus = BusUserModel.objects.filter(delete=False)

        # 分页数据
        paginator = Paginator(bus, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list


        bus_list = []
        for i in data:
            bus_list.append({
                'id':i.id,
                'username':i.b_name,
                'nickname':i.nickname,
                'portrait':i.portrait,
                'gender':i.gender,
                'mobile':i.mobile,
                'person':i.person,
                'business_time':i.business_time,
                'member':i.member,
                'freeze':i.freeze,
                'establish_time':datetime.strftime(i.establish_time,'%Y-%m-%d %H:%M:%S'),
                'change_time':i.change_time,
                'delete':i.delete,
            })
        return Response({
            'code':20000,
            'message':'获取成功',
            'data':bus_list,
            'total': bus.count()
        })

    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        person = request.data.get('person')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')

        if not all([username,password,mobile,person,gender,portrait]):
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        user = BusUserModel.objects.filter(b_name=username).first()
        if user:
            return Response({
                'code': 40000,
                'message': '用户名不可重复'
            })

        users = BusUserModel.objects.filter(mobile=mobile).first()

        if users:
            return Response({
                'code': 40000,
                'message': '手机号不可重复'
            })
        # 密码加密
        password = generate_password_hash(password)

        BusUserModel.objects.create(
            b_name=username,
            password=password,
            mobile=mobile,
            person=person,
            gender=gender,
            portrait=portrait,
        )

        return Response({
            'code': 20000,
            'message': '添加成功'
        })

    def put(self,request):
        # 接受前端数据
        id = request.data.get('id')
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        person = request.data.get('person')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')

        if not all([id,username,mobile,person,gender,portrait]):
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })
        try:
            bus_user = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        bus_user.b_name = username
        if password:
            password = generate_password_hash(password)
            bus_user.password = password

        bus_user.mobile = mobile
        bus_user.person = person
        bus_user.gender = gender
        bus_user.portrait = portrait
        bus_user.save()

        return Response({
            'code':20000,
            'message':'修改成功'
        })

    def delete(self,request):
        # 获取前端数据
        id = request.query_params.get('id')

        try:
            bus_user = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        bus_user.delete = True
        bus_user.save()

        return Response({
            'code':20000,
            'message':'删除成功'
        })


# 获取单个商家信息
class UserInfoView(APIView):
    def get(self,request,id):
        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'id': bus.id,
                'username': bus.b_name,
                'nickname': bus.nickname,
                'portrait': bus.portrait,
                'gender': bus.gender,
                'mobile': bus.mobile,
                'person': bus.person,
                'business_time': bus.business_time,
                'member': bus.member,
                'freeze': bus.freeze,
                'establish_time': bus.establish_time,
                'change_time': bus.change_time,
                'delete': bus.delete,
            }
        })

    def put(self,request,id):
        # 获取前端数据
        vel = request.data.get('vel')

        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        bus.freeze = int(vel)
        bus.save()

        return Response({
            'code':20000,
            'message':'恢复正常' if vel == 2 else '已冻结'
        })


# 获取客户的信息
class CusUserView(APIView):
    def get(self,request):

        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')

        cus_user = CusUserModel.objects.filter(delete=False)

        # 分页数据
        paginator = Paginator(cus_user, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list




        cus_user_list = []
        for i in data:
            cus_user_list.append({
                'id':i.id,
                'username':i.c_name,
                'nickname':i.nickname,
                'portrait':i.portrait,
                'gender':i.gender,
                'mobile':i.mobile,
                'member':i.member,
                'freeze':i.freeze,
                'establish_time':datetime.strftime(i.establish_time,'%Y-%m-%d %H:%M:%S'),
                'change_time':i.change_time,
                'delete':i.delete,
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':cus_user_list,
            'total':cus_user.count()
        })


    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        member = request.data.get('member')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')
        print('>>>>>>',username, password, mobile, gender, member, portrait)

        if not all([username, password, mobile, gender, member, portrait]):
            return Response({
                'code': 40000,
                'message': '获取数据为空'
            })

        user = CusUserModel.objects.filter(c_name=username).first()
        if user:
            return Response({
                'code': 40000,
                'message': '用户名不可重复'
            })

        users = CusUserModel.objects.filter(mobile=mobile).first()

        if users:
            return Response({
                'code': 40000,
                'message': '手机号不可重复'
            })
        # 密码加密
        password = generate_password_hash(password)

        CusUserModel.objects.create(
            c_name=username,
            password=password,
            mobile=mobile,
            gender=gender,
            member=member,
            portrait=portrait,
        )

        return Response({
            'code': 20000,
            'message': '添加成功'
        })

    def put(self,request):
        # 获取前端数据
        vel = request.data.get('vel')
        id = request.data.get("id")

        try:
            bus = CusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        bus.freeze = int(vel)
        bus.save()

        return Response({
            'code':20000,
            'message':'恢复正常' if vel == 2 else '已冻结'
        })


# 获取单个数据 修改 删除
class CusUserInfoView(APIView):
    def get(self,request,id):
        # 进行获取单个数据
        try:
            cus = CusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'id': cus.id,
                'username': cus.c_name,
                'nickname': cus.nickname,
                'portrait': cus.portrait,
                'gender': cus.gender,
                'mobile': cus.mobile,
                'member': cus.member,
                'freeze': cus.freeze,
                'establish_time': datetime.strftime(cus.establish_time, '%Y-%m-%d %H:%M:%S'),
                'change_time': cus.change_time,
                'delete': cus.delete,
            }
        })

    def put(self,request,id):
        # 获取前端数据
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        member = request.data.get('member')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')
        print('>>>>>>', username, mobile, gender, member, portrait)

        if not all([username, mobile, gender, member, portrait]):
            return Response({
                'code': 40000,
                'message': '获取数据为空'
            })

        # 进行获取单个数据
        try:
            cus = CusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code': 40000,
                'message': '获取失败'
            })

        cus.c_name = username
        if password:
            password = generate_password_hash(password)
            cus.password = password

        cus.mobile = mobile
        cus.member = member
        cus.gender = gender
        cus.portrait = portrait
        cus.save()

        return Response({
            'code':20000,
            'message':'修改成功',
        })


    def delete(self,request,id):
        # 进行获取单个数据
        try:
            cus = CusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code': 40000,
                'message': '获取失败'
            })

        cus.delete = True

        cus.save()
        return Response({
            'code':20000,
            'message':'删除成功'
        })

# 获取骑手的信息
class RidUserView(APIView):
    def get(self,request):
        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')
        name = request.query_params.get('name')

        if name:
            rid_user = RiderModel.objects.filter(delete=False,r_name=name)

            # 分页数据
            paginator = Paginator(rid_user, pageSize)
            # 获取当前页面  currentPage：页码
            page = paginator.page(currentPage)

            # 获取当前页面中的数据(商品对象) object_list:查询集
            data = page.object_list

            rid_user_list = []
            for i in data:
                rid_user_list.append({
                    'id':i.id,
                    'username':i.r_name,
                    'mobile':i.mobile,
                    'password':i.password,
                    'portrait':i.img,
                    'login_time':i.login_time,
                    'intro':i.intro,
                    'status':i.status,
                    'freeze':i.freeze,
                    'change_time':i.change_time,
                    'delete':i.delete,
                    'reg_time':datetime.strftime(i.reg_time,'%Y-%m-%d %H:%M:%S'),
                    'gender':i.gender,

                })

            return Response({
                'code':20000,
                'message':'获取成功',
                'data':rid_user_list,
                'total':rid_user.count(),
            })
        rid_user = RiderModel.objects.filter(delete=False)

        # 分页数据
        paginator = Paginator(rid_user, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        rid_user_list = []
        for i in data:
            rid_user_list.append({
                'id': i.id,
                'username': i.r_name,
                'mobile': i.mobile,
                'password': i.password,
                'portrait': i.img,
                'login_time': i.login_time,
                'intro': i.intro,
                'status': i.status,
                'freeze': i.freeze,
                'change_time': i.change_time,
                'delete': i.delete,
                'reg_time': datetime.strftime(i.reg_time, '%Y-%m-%d %H:%M:%S'),
                'gender': i.gender,

            })

        return Response({
            'code': 20000,
            'message': '获取成功',
            'data': rid_user_list,
            'total': rid_user.count(),
        })




    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        gender = request.data.get('gender')
        status = request.data.get('status')
        portrait = request.data.get('portrait')
        print('>>>>>>',username, password, mobile,gender, status, portrait)

        if not all([username, password, mobile,gender, status, portrait]):
            return Response({
                'code': 40000,
                'message': '获取数据为空'
            })

        user = RiderModel.objects.filter(r_name=username).first()
        if user:
            return Response({
                'code': 40000,
                'message': '用户名不可重复'
            })

        users = RiderModel.objects.filter(mobile=mobile).first()

        if users:
            return Response({
                'code': 40000,
                'message': '手机号不可重复'
            })
        # 密码加密
        password = generate_password_hash(password)

        RiderModel.objects.create(
            r_name=username,
            password=password,
            mobile=mobile,
            img=portrait,
            status=status,
            gender=gender,
        )

        return Response({
            'code': 20000,
            'message': '添加成功'
        })

    def put(self,request):
        # 获取前端数据
        vel = request.data.get('vel')
        id = request.data.get("id")

        try:
            bus = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        bus.freeze = int(vel)
        bus.save()

        return Response({
            'code':20000,
            'message':'恢复正常' if vel == 2 else '已冻结'
        })


# 骑手的获取单个数据 修改 删除
class RidUserInfoView(APIView):
    def get(self,request,id):
        # 进行获取单个数据
        try:
            rid = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'id':rid.id,
                'username':rid.r_name,
                'mobile':rid.mobile,
                'portrait':rid.img,
                'login_time':rid.login_time,
                'intro':rid.intro,
                'status':rid.status,
                'freeze':rid.freeze,
                'change_time':rid.change_time,
                'delete':rid.delete,
                'reg_time':datetime.strftime(rid.reg_time,'%Y-%m-%d %H:%M:%S'),
                'gender':rid.gender,
            }
        })

    def put(self,request,id):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        gender = request.data.get('gender')
        status = request.data.get('status')
        portrait = request.data.get('portrait')
        print('>>>>>>', username, mobile, gender, status,  portrait)

        if not all([username, mobile,gender, status,  portrait]):
            return Response({
                'code': 40000,
                'message': '获取数据为空'
            })

        # 进行获取单个数据
        try:
            rid = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code': 40000,
                'message': '获取失败'
            })

        rid.r_name = username
        if password:
            password = generate_password_hash(password)
            rid.password = password
        rid.status = status
        rid.mobile = mobile
        rid.portrait = portrait
        rid.gender = gender
        rid.save()

        return Response({
            'code':20000,
            'message':'修改成功',
        })


    def delete(self,request,id):
        # 进行获取单个数据
        try:
            cus = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code': 40000,
                'message': '获取失败'
            })

        cus.delete = True

        cus.save()
        return Response({
            'code':20000,
            'message':'删除成功'
        })



from business.models import *
# 商品的删除 畅销 推荐
class GoodDeleteView(APIView):
    def put(self,request,id):
        # 接受前端数据
        vel = request.data.get('vel')
        vel2 = request.data.get('vel2')

        try:
            goods = GoodsModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'修改失败'
            })

        if vel:
            goods.is_demand = int(vel)
            goods.save()
            return Response({
                'code': 20000,
                'message': '已畅销' if vel == '1' else '已取消'
            })

        if vel2:
            goods.is_recommend = int(vel2)
            goods.save()
            return Response({
                'code': 20000,
                'message': '已推荐' if vel2 == '1' else '已取消'
            })

    def delete(self,request,id):
        try:
            goods = GoodsModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'删除失败'
            })

        goods.delete = True
        goods.save()

        return Response({
            'code':20000,
            'message':"删除成功"
        })


# 首页数量统计
class CountView(APIView):
    def get(self,request):
        # 客户的数量
        cus = CusUserModel.objects.filter(delete=False)
        # 商家的数量
        bus = BusUserModel.objects.filter(delete=False)
        # 骑手的数量
        rid = RiderModel.objects.filter(delete=False)
        # 今日订单量
        order = PayOrderModel.objects.all()
        order_count = 0
        for i in order:
            if datetime.strftime(i.establish_time,'%Y-%m-%d') == datetime.strftime(datetime.now(),'%Y-%m-%d'):
                order_count += 1
        # 今日客户注册量
        cus_count = 0
        for i in cus:
            if datetime.strftime(i.establish_time,'%Y-%m-%d') == datetime.strftime(datetime.now(),'%Y-%m-%d'):
                cus_count += 1
        # 今日商家注册量
        bus_count = 0
        for i in bus:
            if datetime.strftime(i.establish_time, '%Y-%m-%d') == datetime.strftime(datetime.now(), '%Y-%m-%d'):
                bus_count += 1
        # 今日骑手注册量
        rid_count = 0
        for i in rid:
            if datetime.strftime(i.reg_time, '%Y-%m-%d') == datetime.strftime(datetime.now(), '%Y-%m-%d'):
                rid_count += 1
        # 今日营业额
        order_price = PayOrderModel.objects.filter(status='2')
        price = 0
        for i in order_price:
            price += int(i.amount)

        # 今日商品发布量
        good = GoodsModel.objects.filter(delete=False)
        good_count = 0
        for i in good:
            if datetime.strftime(i.establish_time, '%Y-%m-%d') == datetime.strftime(datetime.now(), '%Y-%m-%d'):
                good_count += 1

        return Response({
            'code':20000,
            'message':'计算成功',
            'data':{
                'cus':cus.count(),
                'bus': bus.count(),
                'rid': rid.count(),
                'order_count':order_count,
                'cus_count':cus_count,
                'bus_count':bus_count,
                'rid_count':rid_count,
                "price":price,
                'good_count':good_count,
            }
        })


# 获取商家没有审核的数据
class AuditView(APIView):
    def get(self,request):

        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')

        bus = BusUserModel.objects.filter(is_audit=3)

        # 分页数据
        paginator = Paginator(bus, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list


        bus_list = []
        for i in data:
            bus_list.append({
                'id':i.id,
                'b_name':i.b_name,
                'nickname':i.nickname,
                'portrait':i.portrait,
                'gender':i.gender,
                'mobile':i.mobile,
                'person':i.person,
                'identity':i.identity,
                'facade':i.facade,
                'plaque':i.plaque,
                'environment':i.environment,
                'business':i.business,
                'hand_identity':i.hand_identity,
                'identity_front':i.identity_front,
                'identity_reverse':i.identity_reverse,
                'business_time':i.business_time,
                'member':i.member,
                'freeze':i.freeze,
                'is_audit':i.is_audit,
                'reject_content':i.reject_content,
                'establish_time':i.establish_time,
                'change_time':i.change_time,
                'delete':i.delete,
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':bus_list,
            'total':bus.count()
        })

    def post(self,request):
        id = request.data.get('id')
        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'数据获取失败',
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'id': bus.id,
                'b_name': bus.b_name,
                'nickname': bus.nickname,
                'portrait': bus.portrait,
                'gender': bus.gender,
                'mobile': bus.mobile,
                'person': bus.person,
                'identity': bus.identity,
                'facade': bus.facade,
                'plaque': bus.plaque,
                'environment': bus.environment,
                'business': bus.business,
                'hand_identity': bus.hand_identity,
                'identity_front': bus.identity_front,
                'identity_reverse': bus.identity_reverse,
                'business_time': bus.business_time,
                'member': bus.member,
                'freeze': bus.freeze,
                'is_audit': bus.is_audit,
                'reject_content': bus.reject_content,
                'establish_time': bus.establish_time,
                'change_time': bus.change_time,
                'delete': bus.delete,
            }
        })

    def put(self,request):
        # 接受前端数据
        id = request.data.get('id')

        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败',
            })

        bus.is_audit = 1
        bus.save()

        return Response({
            'code':20000,
            'message':'审核成功',
        })

    def delete(self,request):
        id = request.query_params.get('id')
        cause = request.query_params.get('cause')

        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败',
            })

        bus.is_audit = 2
        bus.cause_down = cause
        bus.save()

        return Response({
            'code': 20000,
            'message': '驳回成功',
        })









